package com.cy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 服务的消费方
 */
@SpringBootApplication
public class NacosConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(NacosConsumerApplication.class, args);
    }

    /**
     * 初始化RestTemplate对象(Spring提供)，基于此对象
     * 可以通过http协议调用远程服务
     */
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    @Bean
    @LoadBalanced
    public RestTemplate loadBalancedTemplate(){
        return new RestTemplate();
    }

    @Value("${spring.application.name}")
    private String applicationName;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @RestController
    public class ConsumerController {
        @GetMapping("/consumer/doRestEcho")
        public String doRestEcho() {
            ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-provider");
            String host = serviceInstance.getHost();
            int port = serviceInstance.getPort();
            String url = String.format("http://%s:%s/provider/echo/%s", host, port, applicationName);
//            String url = "http://" + host + ":" + port + "provider/echo/" + applicationName;
//            String url="http://localhost:8081/provider/echo/"+applicationName;
            System.out.println("url"+url);
            return restTemplate.getForObject(url, String.class);
        }
    }
}
